﻿using Microsoft.AspNetCore.Mvc.Filters;
using System.Net;
using System.Net.Sockets;

namespace B.S.Warehouse.Write.Api
{
    public class ExceptionFilter : IExceptionFilter
    {
        private readonly ILogger<ExceptionFilter> logger;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="logger"></param>
        public ExceptionFilter(ILogger<ExceptionFilter> logger)
        {
            this.logger = logger;
        }

        public void OnException(ExceptionContext context)
        {
            var hostName = Dns.GetHostName();
            var hostEntry = Dns.GetHostEntry(hostName);
            var ipAddress = hostEntry.AddressList.FirstOrDefault(ip => ip.AddressFamily == AddressFamily.InterNetwork);
            logger.LogError(ipAddress + context.Exception.StackTrace.Substring(0, 50) + "发生了异常");
            context.ExceptionHandled = true;
        }
    }
}
